import React, { useState, useEffect } from "react";
import MyEditor from "./editor.tsx";
import { Flex, Layout, Button, Input, message, Modal } from "antd";
import { useLocation } from "react-router-dom";
import {
  userGetArticleToEdit,
  userPublishArticle,
} from "@/apis/articlesApi.ts";
import { saveDraft, getDraftDetail } from "@/apis/draftApi.ts";

const { Header, Content } = Layout;

const headerStyle: React.CSSProperties = {
  display: "flex",
  justifyContent: "space-between",
  alignItems: "center",
  color: "#fff",
  height: 64,
  paddingInline: 48,
  lineHeight: "50px",
  backgroundColor: "#fff",
};

const contentStyle: React.CSSProperties = {
  // textAlign: "center",
  minHeight: 500,
  // lineHeight: "500px",
  color: "#fff",
  backgroundColor: "#0958d9",
};

const layoutStyle = {
  // borderRadius: 8,
  overflow: "hidden",
  // width: "calc(50% - 8px)",
  // maxWidth: "calc(50% - 8px)",
};

const Editor: React.FC = () => {
  const location = useLocation();
  const [title, setTitle] = useState("");
  const [articleContent, setArticleContent] = useState("");
  const [summary, setSummary] = useState("暂无摘要");

  const params = new URLSearchParams(location.search);

  const _id = params.get("_id");
  const draftId = params.get("draftId");

  // 弹窗逻辑
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 弹窗显示逻辑
  const showModal = () => {
    setIsModalOpen(true);
  };

  // 弹窗确认逻辑
  const handleOk = () => {
    setIsModalOpen(false);
  };

  // 弹窗取消逻辑
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const judgeIsArticle = async () => {
    if (_id) {
      // 说明是编辑文章
      const res = await userGetArticleToEdit(_id);
      console.log(res.data);
      console.log("_id: ", _id);
      console.log("articleContent: ", articleContent);
      setTitle(res.data?.title!);
      setArticleContent(res.data?.content!);
    } else if (draftId) {
      // 说明是新建文章
      const res = await getDraftDetail(draftId);

      // 先将草稿内容设置到编辑器中
      console.log(res.data);
      setTitle(res.data?.title!);
      setArticleContent(res.data?.content!);
    }
  };

  useEffect(() => {
    judgeIsArticle();
  }, []);

  // 保存草稿逻辑
  const handleSaveDraft = async () => {
    console.log("at 保存草稿 title", title);
    console.log("content at 保存草稿", articleContent);
    const myDraftId = draftId || "";

    // 保存草稿
    const res = await saveDraft({
      title,
      content: articleContent.trim(),
      draftId: myDraftId,
      summary,
      createTime: new Date().toString(),
    });

    if (res.code === 200) {
      console.log("保存草稿成功", res.data);
      window.history.go(-1);
    } else {
      console.log("保存草稿失败");
    }

    // 关闭弹窗
    setIsModalOpen(false);
  };

  // 发布文章逻辑
  const handlePublish = async () => {
    console.log("at 发布文章 title", title);
    console.log("content at 发布文章", articleContent);

    // 判断标题和内容是否为空
    if (!title || !articleContent) {
      // 提示错误信息
      message.error("标题和内容不能为空");

      // 直接返回，不执行发布文章逻辑
      return;
    }

    if (_id) {
      // 说明是编辑文章
      const res = await userPublishArticle({
        title,
        content: articleContent.trim(),
        articleId: _id,
        summary,
        createTime: new Date().toString(),
      });

      // 判断文章是否发送成功
      if (res.code === 200) {
        console.log("发布文章成功", res.data);

        // 跳转到上一页
        window.history.go(-1);
      }
    } else if (draftId) {
      // 说明是新建文章
      const res = await userPublishArticle({
        title,
        content: articleContent.trim(),
        summary,
        draftId,
        createTime: new Date().toString(),
      });

      // 判断文章是否发送成功
      if (res.code === 200) {
        console.log("发布文章成功", res.data);
        // 跳转到上一页
        window.history.go(-1);
      }
    }

    // 关闭弹窗
    setIsModalOpen(false);
  };

  return (
    <Flex gap="middle" wrap>
      <Layout style={layoutStyle}>
        <Header style={headerStyle}>
          <Input
            style={{ height: "40px" }}
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="请输入标题"
          />
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              flexGrow: 1,
              paddingLeft: "20px",
            }}
          >
            <Button onClick={showModal} type="primary">
              保存草稿
            </Button>
            <Button onClick={showModal} type="primary">
              发布文章
            </Button>
          </div>
        </Header>
        <Content style={contentStyle}>
          <MyEditor
            content={articleContent}
            setArticleContent={(newContent) => setArticleContent(newContent)}
            articleId={_id ? _id! : draftId!}
          />
        </Content>
        <Modal
          title="Basic Modal"
          footer={null}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Input.TextArea
            autoSize={{ minRows: 4, maxRows: 10 }}
            value={summary}
            onChange={(e) => setSummary(e.target.value)}
          />
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              flexGrow: 1,
              paddingLeft: "20px",
            }}
          >
            <Button onClick={handleSaveDraft} type="primary">
              保存草稿
            </Button>
            <Button onClick={handlePublish} type="primary">
              发布文章
            </Button>
          </div>
        </Modal>
      </Layout>
    </Flex>
  );
};

export default Editor;
